package atessitura;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
//import java.io.FileFilter;

import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileFilter;

import org.apache.commons.vfs2.*;

import custom.JarFileChooser;

import tuner.Tuner;
import tuner.TunerFrame;


public class TFController 
{
	private TFrame view;
	private TModel model;
	private float percentage;
	private File song;
	private ArrayList<GuitarNote>[][] array;
	private TFileManager fileManager;
	
	public TFController()
	{
		model=new TModel(this);
		view = new TFrame(this);
		view.setLocationRelativeTo(null);
		view.setVisible(true);
		
		fileManager=null;
		//percentage=0;
	}
	
	//Menu Methods
	public void menuNew() {
		model.menuNew();
		
	}
	
	public void menuOpen() 
	{
		JFileChooser fileDialog = new JFileChooser();
		/*String path=new File(".").getAbsolutePath();
		path=path.substring(0,path.length()-1);
		path+="Imported Midi/";*/
		String path="";
		String OSName=System.getProperty("os.name");
		if(OSName.contains("Windows"))
		{
			path="C:/Program Files/Tessitura/Imported Midi/";
		}
		else
		{
			boolean success = (new File("/Applications/Tessitura/Imported Midi/")).mkdirs();
			path="/Applications/Tessitura/Imported Midi/";
		}
		
		fileDialog.setCurrentDirectory(new File(path));
		FileFilter midiFilter=new FileFilter(){

			@Override
			public boolean accept(File fileChosen) {
				return fileChosen.getName().endsWith(".mid");
			}

			@Override
			public String getDescription() {
				// TODO Auto-generated method stub
				return "MIDI";
			}
			
		};
		fileDialog.setFileFilter((javax.swing.filechooser.FileFilter) midiFilter);
		int openChoice = fileDialog.showOpenDialog(view);
		File openFile=null;
		if (openChoice == JFileChooser.APPROVE_OPTION)
        {
            //Put open file code in here
             openFile= fileDialog.getSelectedFile();
             song = openFile;
        }
		String songName = openFile.getName();
		System.out.println (songName);
		songName = songName.substring (0,songName.length()-4);
		File textFile;
		textFile = new File ("Imported Songs/" + songName + ".txt");
		if (System.getProperty("os.name").contains("Windows"))
		{
			textFile = new File(("C:/Program Files/Tessitura/Imported Songs/" +songName + ".txt"));
		}
		else
		{
			textFile = new File(("/Applications/Tessitura/Imported Songs/" +songName + ".txt"));
		}
		 
		try{
			fileManager = new TFileManager(textFile);
			model.menuOpen(openFile);
			view.setSongName(openFile.getName().substring(0,openFile.getName().length()-4));
		}catch(Exception e)
		{
			e.printStackTrace();
		}
		view.setUpCPanel();
		array = new ArrayList[model.getNumTracks()][0];
		for (int x=0; x< array.length; x++)
		{
			array[x] = model.getNotesFromTrack(x);
		}
		
		
		
		
	}
	
	public void menuOpenExample() {
		
		try {
			String pathie=new File(".").getAbsolutePath();
			pathie=pathie.substring(0,pathie.length()-1);
			JarFile sexyFile=new JarFile(new File(pathie+"Tessitura.jar"));
			
			JarEntry picked=null;
			
			JarFileChooser chooser=new JarFileChooser(sexyFile,"Example Songs", this);
			
			for(Enumeration e=sexyFile.entries();e.hasMoreElements();)
			{
				JarEntry now=(JarEntry)e.nextElement();
				if(now.toString().equals("resources/Example Songs/Bach__Minuet_in_G_major.mid"))
				{
					picked=now;
				}
			}
			
			
			
		} catch (IOException e1) {
			e1.printStackTrace();
			
			
			JFileChooser fileDialog = new JFileChooser();
			
			String path=new File(".").getAbsolutePath();
			path=path.substring(0,path.length()-1);
			path+="Example Songs/";
			fileDialog.setCurrentDirectory(new File(path));
			FileFilter midiFilter=new FileFilter(){

				@Override
				public boolean accept(File fileChosen) {
					return fileChosen.getName().endsWith(".mid");
				}

				@Override
				public String getDescription() {
					// TODO Auto-generated method stub
					return "MIDI";
				}
				
			};
			fileDialog.setFileFilter((javax.swing.filechooser.FileFilter) midiFilter);
			int openChoice = fileDialog.showOpenDialog(view);
			File openFile=null;
			if (openChoice == JFileChooser.APPROVE_OPTION)
	        {
	            //Put open file code in here
	             openFile= fileDialog.getSelectedFile();
	             song = openFile;
	        }
			
			try{
				fileManager=null;
				model.menuImport(openFile);
				view.setSongName(openFile.getName().substring(0,openFile.getName().length()-4));
			}catch(Exception e)
			{
				
			}
			view.setUpCPanel();
			array = new ArrayList[model.getNumTracks()][0];
			for (int x=0; x< array.length; x++)
			{
				array[x] = model.getNotesFromTrack(x);
			}
			//KFrame k=new KFrame();
			//EFrame e = new EFrame();
		}
		
	}
	
	public void openExampleFilePicked(JarFile sexyFile, JarEntry picked)
	{
		try{
			InputStream input=sexyFile.getInputStream(picked);
			
			//File songFile=File.createTempFile("songFile", ".mid");
			System.out.println(picked.getName()+" "+sexyFile.getName());
			String now=picked.getName();
			String songString=now.substring(now.indexOf("Example Songs/")+(14));
			
			File songFile=new File(songString);
			songFile.deleteOnExit();
			OutputStream out=new FileOutputStream(songFile);
			
			int read=0;
			byte[] bytes=new byte[1024];
			
			while((read=input.read(bytes))!=-1)
			{
				out.write(bytes,0,read);
			}
			
			input.close();
			out.flush();
			out.close();
			
			song=songFile;
			
			try{
				fileManager=null;
				model.menuImport(songFile);
				view.setSongName(songFile.getName().substring(0,songFile.getName().length()-4));
			}catch(Exception e)
			{
				
			}
			view.setUpCPanel();
			array = new ArrayList[model.getNumTracks()][0];
			for (int x=0; x< array.length; x++)
			{
				array[x] = model.getNotesFromTrack(x);
			}
		}catch(Exception e)
		{
			e.printStackTrace();
		}
		
	}

	public void menuImport() throws IOException {
		// TODO Auto-generated method stub
		JFileChooser fileDialog = new JFileChooser();
		FileFilter midiFilter=new FileFilter(){

			@Override
			public boolean accept(File fileChosen) {
				return fileChosen.getName().endsWith(".mid");
			}

			@Override
			public String getDescription() {
				// TODO Auto-generated method stub
				return "MIDI";
			}
			
		};
	//	fileDialog.setFileFilter((javax.swing.filechooser.FileFilter) midiFilter);
		int openChoice = fileDialog.showOpenDialog(view);
		File openFile=null;
		if (openChoice == JFileChooser.APPROVE_OPTION)
        {
            //Put open file code in here
             openFile= fileDialog.getSelectedFile();
             song = openFile;
        }
		
		try{
			fileManager=null;
			model.menuImport(openFile);
			view.setSongName(openFile.getName().substring(0,openFile.getName().length()-4));
		}catch(Exception e)
		{
			
		}
		view.setUpCPanel();
		
		array = new ArrayList[model.getNumTracks()][0];
		for (int x=0; x< array.length; x++)
		{
			array[x] = model.getNotesFromTrack(x);
		}
		
		
		//System.out.println ("File manager created");
	//	KFrame k=new KFrame();
	}

	public void menuExportMIDI() {
		// TODO Auto-generated method stub
		
	}

	public void menuExportMP3() {
		// TODO Auto-generated method stub
		
	}

	public void menuExportWAV() {
		// TODO Auto-generated method stub
		
	}

	public void menuPreferences() {
		// TODO Auto-generated method stub
		
	}

	public void menuScoreInfo() {
		// TODO Auto-generated method stub
		
	}

	
	//General Sound
	public void play() {
		model.play();
		
	}
	
	public void stop() {
		model.stop();
		
	}

	public void playpauseswitch(boolean play)
	{
		view.playpauseswitch(play);
	}
	
	public void rewind() {
		// TODO Auto-generated method stub
		
	}

	public void metronome() {
		// TODO Auto-generated method stub
		
	}

	public void tuner() 
	{
		try {
			TunerFrame tune = new TunerFrame();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//Tuner tuner =  new Tuner ();
		//tuner.playPitch(38); // a D
		
	}
	public void setNoteName (String note){
		view.setNoteName(note);
	}
	
	
	
	//get
	/*public double getPercentagePerMillisecond()
	{
		return .50;
	}
	
	public float getPercentagePerTick()
	{
		System.out.println("LOOK AT ME I NEED ATTENTION	 "+((float)getPercentagePerMillisecond()/1000)/model.getOneTickLength());
		return ((float)getPercentagePerMillisecond()/1000)/model.getOneTickLength();
	}*/
	
	public float getPercentagePerTick()
	{
		return percentage;
	}
	
	public double getMillisecondPosition()
	{
		return model.getMillisecondPosition();
	}
	
	public double getTickPosition()
	{
		return model.getTickPosition();
	}
	
	public int getNumTracks()
	{
		return model.getNumTracks();
	}

	//set
	public void setViewNotes(ArrayList<GuitarNote>[] notes) {
		
		view.setNotes(notes);
	}

	public void incrementalGUIUpdate(double percentPlayed) {
		repaintGPanel();
		updateTime(percentPlayed);
	}
	
	public void repaintGPanel()
	{
		view.repaintGPanel();
	}
	
	public void updateTime(double percentPlayed)
	{
		view.updateTime(percentPlayed);
	}
	
	public void setPercentage(float perc)
	{
		percentage=perc;
	}

	public void setTime(int value) {
		model.setTime(value);
	}
	
	public void setTempoFactor(double tempoFactor)
	{
		view.setTempoFactor(tempoFactor);
		model.setTempoFactor(tempoFactor);
	}
	
	public void setLooping(boolean loop)
	{
		model.setLooping(loop);
	}

	public void octaveUp() {
		model.octaveUp();
		
	}
	
	public void octaveDown(){
		model.octaveDown();
	}

	public void setCurrentGuitarTrack(int track) {
		model.setCurrentGuitarTrack(track);
	}
	
	public String getStringTime()
	{
		return model.getStringTime();
	}
	
	public String getStringTimeLength()
	{
		return model.getStringTimeLength();
	}
	public void save () throws IOException	{
		//System.out.println (song.getAbsolutePath());
		TFileManager fileManager = new TFileManager (song,array, song.getName());
	}

	public boolean isPaused() {
		// TODO Auto-generated method stub
		return model.isPaused();
	}

	public ArrayList<GuitarNote>[] getGuitarTrack(int track) {
		// TODO Auto-generated method stub
		try{
			return fileManager.readNotes()[track];
		}catch(Exception e)
		{
			return null;
		}
	}
	
	
}
